# This Python file uses the following encoding: utf-8
import shutil
import subprocess
from typing import Iterator
import time

import requests
import json
import logging

group_id = "1782363907101311147"
api_key = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmt7HlnLPnp5HliJvlrabpmaIiLCJVc2VyTmFtZSI6Iua3seWcs-enkeWIm-WtpumZoiIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxNzgyMzYzOTA3MTA5Njk5NzU1IiwiUGhvbmUiOiIxOTk3MzMxODc5NSIsIkdyb3VwSUQiOiIxNzgyMzYzOTA3MTAxMzExMTQ3IiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjQtMDUtMDIgMTU6NTU6NDYiLCJpc3MiOiJtaW5pbWF4In0.t45S7_Jrm0bUeNLI8N_Q5alSw1JR1d8LhZv84eAy69MENNbEzvABhPjEpz8-7-9pnQGBuCYlMIE8w9sC2PkjpXyhM_vr5GHOBeQt3S2VYN2pwUK295wTarh6lt1LesSA9053KFQWEWWlQnu48peblLQY6jyCJOifM7otDxvyvajuDc_aYWdSTjCpOl3YwBgr5hKniQaU9tVUm8bi88_ZuKpi2Qu3LC0owYOyR57rbTZjggZgXj2lQoarcRk0OJAb14Vti3STLmEcNErFEEdwSs3f6W-gqVsqkHkrd5T_SnjqCMvGBVqfhMVie-z3-VVFCtuc1XBaY0WYeUGz9AJ2Pw"
file_format='mp3'     
# 支持 mp3/pcm/flac

def build_tts_stream_headers() -> dict:
   headers =   {
    'accept': 'application/json, text/plain, */*',
    'content-type': 'application/json',
    'authorization':  "Bearer "+api_key,
  }
   return headers

def build_tts_stream_body() -> dict:
  body =  json.dumps({
    "timber_weights": [
      {
        "voice_id": "Cuteboy_platform",
        "weight": 1
      },
      {
        "voice_id": "female-shaonv",
        "weight": 0
      }
    ],
    "text": "你好呀Zorky，我是你的神奇海螺，你有什么要问我的吗？",
    "voice_id": "",
    "model": "speech-01",
    "speed": 1,
    "vol": 1,
    "pitch": 0,
    "audio_sample_rate": 32000,
    "bitrate": 128000,
    "format": file_format,
  })
  return body

def call_tts_stream() -> Iterator[bytes]:
  url = "https://api.minimax.chat/v1/tts/stream?GroupId="+ group_id
  headers = build_tts_stream_headers()
  body = build_tts_stream_body()
  response =  requests.request("POST", url, stream=True, headers=headers, data=body)
  
  print("Trace-Id: "+ response.headers.get("Trace-Id"))
  for chunk in (response.raw):
    if chunk:
        if chunk[:5] == b'data:':
          data = json.loads(chunk[5:])
          if "data" in data and "extra_info" not in data:
            if "audio" in data["data"] :
              audio =data["data"]['audio']
              yield audio
        else:
           print(str(chunk))

def is_installed(lib_name: str) -> bool:
  lib = shutil.which(lib_name)
  if lib is None:
      return False
  return True

def audio_play(audio_stream: Iterator[bytes]) -> bytes:
  if not is_installed("mpv"):
      message = (
          "本示例使用 mpv 播放音频，检测到您未安装"
          "您可使用 'brew install mpv' 安装，或访问官方网站 https://mpv.io/ 获取更多信息"
          "同时您也可以使用其他的合适的方式播放音频"
      )
      raise ValueError(message)

  mpv_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"]
  mpv_process = subprocess.Popen(
      mpv_command,
      stdin=subprocess.PIPE,
      stdout=subprocess.DEVNULL,
      stderr=subprocess.DEVNULL,
  )

  audio = b""
  
  for chunk in audio_stream:
      if chunk is not None:
          decoded_hex = bytes.fromhex(chunk)
          # 播放该段音频
          mpv_process.stdin.write(decoded_hex)
          mpv_process.stdin.flush()  
        
          audio += decoded_hex

  if mpv_process.stdin:
      mpv_process.stdin.close()
  mpv_process.wait()

  return audio

audio_chunk_iterator = call_tts_stream()
audio = audio_play(audio_chunk_iterator)

# 结果保存至文件
timestamp = int(time.time())
file_name=f'output_{timestamp}.{file_format}'
with open(file_name, 'wb') as file:
    file.write(audio)